import { Component,OnInit,Inject } from '@angular/core';
import { MatDialog,MatDialogRef,MAT_DIALOG_DATA } from '@angular/material/dialog';

import { HmiService } from '../../_services/hmi.service';
import { HttpClient } from '@angular/common/http';
import { Device,DEVICE_PREFIX, DeviceNetProperty,Tag,TAG_PREFIX  } from '../../_models/device';
import { ProjectService } from '../../_services/project.service';
import { GaugeSettings } from '../../_models/hmi';
// import { DeviceTagDialog } from './../../device/device.component';
import { Utils } from '../../_helpers/utils';


@Component({
    selector: 'app-measure-property',
    templateUrl: './measure-property.component.html',
    styleUrls: ['./measure-property.component.css']
})
export class MeasurePropertyComponent implements OnInit {

    constructor(
        private projectService: ProjectService,
        private dialog: MatDialog,
        private hmiService: HmiService,
        public dialogRef: MatDialogRef<MeasurePropertyComponent>,
        private http: HttpClient,
        @Inject(MAT_DIALOG_DATA) public data: any
        ) {
        console.log(data);
        const { variableId,...prop}=data;
        this.variableId=variableId;
        this.data=prop;
        if(data.data.canvasDeviceList){
            data.data.canvasDeviceList.map((cd: any)=>{
                if(!!cd.deviceId){
                    this.canvasDeviceList.push(cd);
                }
            });
        }
    }

    settings: GaugeSettings;

    deviceMeasureList: any[]=[];
    form: any={};
    deviceSelected: Device = null;
    devices: any;
    deviceList: any[];
    dirty = false;

    tagsMap = {};

    url='';

    jsonParam: string;
    kafkaName: string='测试环境kafka';
    host: string='10.39.68.59:9092';
    topic: string='data_iot_device_measure';
    measureCode: string;
    deviceId: string;
    polling: number;

    sameDevice=false;
    variableId: string;

    addKafka=false;
    addTag=false;
    kafkaId: string;
    tagList: Tag[];
    tagId: string;

    canvasDeviceList: any[]=[];
    deviceName: string;
    measureName: string;

    ngOnInit() {
        this.deviceList =Object.values(this.projectService.getDevices()).filter((d: any)=>{
            if(d.type==='Kafka'){return true;}
        });
        if(this.variableId){
            const device=this.projectService.getDeviceFromTagId(this.variableId);
            if(device && device.property){
                this.kafkaId=device.id;
                this.polling=device.polling/1000;
                this.host=device.property.address;
                this.kafkaName=device.name;
                if(device.tags){
                    let tag=device.tags[this.variableId];
                    this.tagList=Object.values(device.tags);
                    this.tagId=tag.id;
                    this.deviceId=tag.deviceId;
                    this.topic=tag.topic;
                    this.getMeasureList(this.deviceId);
                    this.measureCode=tag.measureCode;
                }
            }
        }

        let device: any=Object.values(this.projectService.getDevices()).find((d: any)=>{
            if(d.type==='Kafka' && d.property.address===this.host){return true;}
        });
        if(device){
            this.tagList=Object.values(device.tags);
            console.log(this.tagList);
        }


    }

    onKafkaChange(kafkaId){
        console.log(kafkaId);
        const device=this.deviceList.find(d=>d.id==kafkaId);
        this.host=device.property.address;
        this.kafkaName=device.name;
        this.polling=device.polling/1000;
        this.tagList=Object.values(device.tags);
    }
    onTagChange(tagId){
        console.log(tagId);
        const tag: any=this.tagList.find(d=>d.id==tagId);
        this.topic=tag.topic;
        this.deviceId=tag.deviceId;
        this.measureCode=tag.measureCode;
        this.getMeasureList(this.deviceId);
    }

    onAddKafka(){
        this.kafkaId='';
        this.tagId='';
        this.host='';
        this.kafkaName='';
        this.polling=null;
        this.addKafka=!this.addKafka;
        this.onAddTag();
    }

    onAddTag(){
        this.topic='data_iot_device_measure';
        this.tagId='';
        this.deviceId='';
        this.deviceMeasureList=[];
        this.addTag=!this.addTag;
    }

    getMeasureList(deviceId){
        console.log(this.canvasDeviceList);
        this.deviceName=this.canvasDeviceList.find(cd=>cd.deviceId===deviceId).name;
        if(deviceId){
            this.http.post('/deviceApi/device/mgt/processedDeviceMeasureListPage',{current:1,size:100,deviceId}).subscribe((res: any) => {
                if(res.code===200){
                    this.deviceMeasureList=res.data.list;
                }
            });
        }else{
            this.deviceMeasureList=[];
        }
    }

    // setVariable(tag: Tag) {
    //     console.log('设置tag变量id',tag);
    //     if (tag) {
    //         this.variableId = tag.id;
    //     } else {
    //         this.variableId = null;
    //     }
    //     this.onChanged();
    // }


    onMeasure(){
        console.log(this.deviceId,this.measureCode,this.polling);
        let deviceId=this.deviceId+':'+this.measureCode;
        let device = this.projectService.getDeviceFromId(deviceId);
        console.log(device);
        if(!device){
            this.sameDevice=false;
            // 添加设备时，应该用设备id作为主键
            device = new Device(deviceId);
            // 此处没有设备名称
            device.name=this.deviceId+':'+this.deviceMeasureList.find(dm=>dm.code===this.measureCode).name;
            device.property = new DeviceNetProperty();
            device.property.address='https://iot-device-service-1.dev.ennew.com/device/measureDefinitionListPage';
            device.property.jsonParam={
                keyword:this.measureCode,
                current:1,
                size:10,
                deviceId:this.deviceId,
                dataQueryFlag:true
            };
            device.property.method='POST';
            device.polling=(this.polling || 1)*1000;
            device.enabled = false;
            device.tags = {};
        }else{
            this.sameDevice=true;
            this.tagsMap=device.tags;
        }
        device.type = 'WebAPI';
        device.enabled = true;
        this.editDevice(device);
    }

    onKafka(){
        const deviceId=Utils.getGUID(DEVICE_PREFIX);
        let devices = this.projectService.getDevices();
        let deviceList = devices?Object.values(devices):[];
        let device=null;
        console.log('>>>>>>',deviceList);
        // 一个卡夫卡地址只能创建一个设备
        if(deviceList && deviceList.length){
            device=deviceList.find((d: any)=>d.property && d.property.address===this.host);
        }
        console.log(device);
        if(!device){
            this.sameDevice=false;
            // 添加设备时，应该用设备id作为主键
            device = new Device(deviceId);
            console.log(deviceId);
            // 此处没有设备名称
            device.name=this.kafkaName;
            device.property = new DeviceNetProperty();
            device.property.address=this.host;//'10.39.64.34:9092';
            device.property['topics']=[this.topic];
            device.polling=(this.polling || 1)*1000;
            device.tags = {};
            device.type = 'Kafka';
            device.enabled = true;
        }else{
            // 当设备存在时，topic 可以添加
            let topics: string[]=device.property['topics'];
            if(topics && topics.length){
                if(!topics.includes(this.topic)){
                    device.property['topics'].push(this.topic);
                };
            }
            this.sameDevice=true;
            this.tagsMap=device.tags;
        }
        this.editDevice(device);
    }



    onMeasureCodeChange(measureCode){
        this.measureCode=measureCode;
        this.measureName=this.deviceMeasureList.find(dm=>dm.code===measureCode).name;
    }

    editDevice(device){
        let olddevice = JSON.parse(JSON.stringify(device));
        let tempdevice = JSON.parse(JSON.stringify(device));
        // if (this.appService.isClientApp || this.appService.isDemoApp) {
        //     delete device.property;
        // }
        if (device.property && tempdevice.property) {
            device.property = {...tempdevice.property};
            if (tempdevice.property.connectionOption) {
                device.property.connectionOption = tempdevice.property.connectionOption;
            }
        }
        this.projectService.setDevice(device, olddevice, null);

        this.deviceSelected=device;
        this.addKafkaTags();
        console.log(this.deviceSelected,device);

    }

    addKafkaTags() {
        console.log('点击我',this.deviceSelected, this.devices );
        let tags=Object.values(this.tagsMap);
        let tag: any = tags.find((t: any)=>t.deviceId===this.deviceId && t.measureCode===this.measureCode);
        if(tag){
            this.variableId=tag.id;
            this.deviceSelected.tags=this.tagsMap;
            console.log(tag,this.deviceSelected.tags);
            this.bindToTable(this.deviceSelected.tags);
        }else{
            let tag = new Tag(Utils.getGUID(TAG_PREFIX));
            tag.name = `${this.deviceName}&${this.measureName}`;//`${this.deviceId}的${this.measureCode}`;
            tag.label = this.measureCode;
            tag.type = 'number';
            tag['topic']=this.topic;
            tag['deviceId']=this.deviceId;
            tag['measureCode']=this.measureCode;
            tag.address =  `${this.deviceId}/${this.measureCode}`;
            console.log(tag,this.deviceSelected);
            this.checkToAdd(tag, this.deviceSelected);
            this.projectService.setDeviceTags(this.deviceSelected);
        }

    }


    checkToAdd(tag: Tag, device: Device, overwrite: boolean = false) {
        let exist = false;
        Object.keys(device.tags).forEach((key) => {
            console.log(device.tags[key]);
            if (device.tags[key].id) {
                if (device.tags[key].id === tag.id) {
                    exist = true;
                }
            } else if (device.tags[key].name === tag.name) {
                console.log('111');
                exist = true;
            }
        });
        // console.log(device.tags,tag,exist);
        if (!exist || overwrite) {
            // 说明已经订阅过，需要用之前的tagid,仅保留一个
            device.tags[tag.id] = tag;
        }

        this.tagsMap[tag.id] = tag;
        this.variableId=tag.id;
        this.deviceSelected.tags=this.tagsMap;
        console.log(tag,this.deviceSelected.tags);
        this.bindToTable(this.deviceSelected.tags);
    }

    private bindToTable(tags) {
        console.log(tags);
        if (!tags) {
            tags = {};
        }
        let arr=[];
        Object.values(tags).forEach((item: any)=>{
            arr.push({...item,value:typeof(item.value)==='object'?JSON.stringify(item.value):item.value});
        });
        console.log(',,,,,,,,',Object.keys(tags));
        this.hmiService.tagsSubscribe(Object.keys(tags));
        console.log(this.projectService.getDevices(),this.variableId);
        this.form.variableId=this.variableId;
        this.dialogRef.close(this.form);

    }


    onOkClick(){
        this.onKafka();
    }


    onNoClick(){
        this.dialogRef.close();
    }
}
